<template>
  <div class="achievement-container">
    <div class="dashboard-container">
      <div class="dashboard">
        <!-- 卫生状况图表 -->
        <div class="chart-card">
<!--          <h3 class="chart-title">卫生状况</h3>-->
          <div class="chart-wrapper">
            <v-chart
                ref="hygieneChartRef"
                :option="hygieneChartOptions"
                autoresize
                v-if="!chartError.hygiene"
            />
            <div v-else class="chart-error">图表加载失败</div>
          </div>
        </div>

        <!-- 问题记录图表 -->
        <div class="chart-card">
<!--          <h3 class="chart-title">问题记录</h3>-->
          <div class="chart-wrapper">
            <v-chart
                ref="problemChartRef"
                :option="problemChartOptions"
                autoresize
                v-if="!chartError.problem"
            />
            <div v-else class="chart-error">图表加载失败</div>
          </div>
        </div>

        <!-- 检查趋势图表 -->
        <div class="chart-card">
<!--          <h3 class="chart-title">检查趋势</h3>-->
          <div class="chart-wrapper">
            <v-chart
                ref="inspectionChartRef"
                :option="inspectionChartOptions"
                autoresize
                v-if="!chartError.inspection"
            />
            <div v-else class="chart-error">图表加载失败</div>
          </div>
        </div>

        <!-- AI数据分析模块 -->
        <div class="ai-card">
          <h3 class="ai-title">AI数据分析</h3>
          <div class="ai-content" v-html="formattedAiMessage"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';

// 图表配置和状态
const chartError = ref({
  hygiene: false,
  problem: false,
  inspection: false
});

const hygieneChartOptions = ref({
  title: { text: '加载中...', left: 'center' }
});
const problemChartOptions = ref({
  title: { text: '加载中...', left: 'center' }
});
const inspectionChartOptions = ref({
  title: { text: '加载中...', left: 'center' }
});

// AI消息处理
const aiMessage = ref("正在获取分析数据...");
const formattedAiMessage = computed(() => {
  if (!aiMessage.value) return '';
  // 安全处理HTML转义
  const safeHtml = aiMessage.value
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
      .replace(/\n/g, '<br>');
  return safeHtml;
});

// 获取图表数据
const fetchChartData = async () => {
  try {
    const response = await axios.get(
        'http://47.113.195.131:8122/api/DormitoryInspectionRecord/getInspectionStatistics',
        { timeout: 5000 } // 添加超时设置
    );

    // 验证数据格式
    if (!response.data?.data?.hygieneStats ||
        !response.data?.data?.problemTypeStats ||
        !response.data?.data?.inspectionTrend) {
      throw new Error('返回数据格式不正确');
    }

    return response.data.data;
  } catch (error) {
    console.error('获取图表数据失败:', error);
    throw error;
  }
};

// 获取AI分析结果
const fetchAnalysisData = async (payload) => {
  try {
    const response = await axios.post(
        'http://47.113.195.131:8122/api/DormitoryInspectionRecord/analyzeInspectionData',
        {
          hygieneStats: payload.hygieneStats.map(item => ({
            count: Number(item.count) || 0,
            hygieneStatus: Number(item.hygiene_status) || 0
          })),
          inspectionTrend: payload.inspectionTrend.map(item => ({
            count: Number(item.count) || 0,
            date: item.date || ''
          })),
          problemStats: payload.problemTypeStats.map(item => ({
            count: Number(item.count) || 0,
            problemType: Number(item.problem_type) || 0
          }))
        },
        { timeout: 8000 } // AI分析可能需要更长时间
    );

    // 验证返回数据
    if (!response.data && !response.data.message && !response.data.data) {
      throw new Error('AI分析返回数据无效');
    }

    return response.data;
  } catch (error) {
    console.error('获取AI分析失败:', error);
    throw error;
  }
};

// 主流程
const processData = async () => {
  try {
    // 重置状态
    chartError.value = {
      hygiene: false,
      problem: false,
      inspection: false
    };

    // 1. 获取基础数据
    const chartData = await fetchChartData();

    // 2. 准备AI分析请求数据
    const analysisPayload = {
      hygieneStats: chartData.hygieneStats,
      inspectionTrend: chartData.inspectionTrend,
      problemTypeStats: chartData.problemTypeStats
    };

    // 3. 并发请求
    const [_, analysisResult] = await Promise.all([
      renderCharts(chartData),
      fetchAnalysisData(analysisPayload)
    ]);

    // 4. 处理AI结果
    aiMessage.value = analysisResult.data ||
        analysisResult.message ||
        "​**​分析完成​**​<br>暂无详细建议";

  } catch (error) {
    console.error('数据处理出错:', error);
    aiMessage.value = "​**​系统提示​**​<br>数据加载异常，请稍后重试";

    // 标记所有图表为错误状态
    chartError.value = {
      hygiene: true,
      problem: true,
      inspection: true
    };
  }
};

// 渲染图表（使用您喜欢的样式）
const renderCharts = (data) => {
  try {
    // 卫生状况图表（饼图）
    hygieneChartOptions.value = {
      title: {
        text: '卫生状况',
        left: 'center',
        textStyle: { fontSize: 16 }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        bottom: 10,
        data: data.hygieneStats.map(item => getHygieneStatus(item.hygiene_status))
      },
      series: [{
        name: '卫生状况',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {c}',
          fontSize: 12
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          }
        },
        data: data.hygieneStats.map(item => ({
          value: item.count,
          name: getHygieneStatus(item.hygiene_status),
          itemStyle: {
            color: getHygieneColor(item.hygiene_status)
          }
        }))
      }]
    };
  } catch (e) {
    console.error('渲染卫生图表出错:', e);
    chartError.value.hygiene = true;
  }

  try {
    // 问题记录图表（饼图）
    problemChartOptions.value = {
      title: {
        text: '问题记录',
        left: 'center',
        textStyle: { fontSize: 16 }
      },
      tooltip: {
        trigger: 'item',
        formatter: '{b}: {c} ({d}%)'
      },
      legend: {
        bottom: 10,
        data: data.problemTypeStats.map(item => getProblemType(item.problem_type))
      },
      series: [{
        name: '问题类型',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 8,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          formatter: '{b}: {c}',
          fontSize: 12
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold'
          }
        },
        data: data.problemTypeStats.map(item => ({
          value: item.count,
          name: getProblemType(item.problem_type),
          itemStyle: {
            color: getProblemColor(item.problem_type)
          }
        }))
      }]
    };
  } catch (e) {
    console.error('渲染问题图表出错:', e);
    chartError.value.problem = true;
  }

  try {
    // 检查趋势图表（柱状图）
    inspectionChartOptions.value = {
      title: {
        text: '检查趋势',
        left: 'center',
        textStyle: { fontSize: 16 }
      },
      tooltip: {
        trigger: 'axis',
        axisPointer: { type: 'shadow' },
        formatter: '{b}<br/>数量: {c}'
      },
      grid: {
        left: '3%',
        right: '4%',
        bottom: '12%',
        containLabel: true
      },
      xAxis: {
        type: 'category',
        data: data.inspectionTrend.map(item => formatDate(item.date)),
        axisLabel: {
          rotate: 30,
          fontSize: 12
        },
        axisTick: {
          alignWithLabel: true
        }
      },
      yAxis: {
        type: 'value',
        axisLabel: { fontSize: 12 }
      },
      series: [{
        name: '数量',
        type: 'bar',
        barWidth: '60%',
        data: data.inspectionTrend.map(item => item.count),
        itemStyle: {
          color: function(params) {
            const colors = ['#FF6B81', '#FFA07A', '#98FB98', '#87CEFA'];
            return colors[params.dataIndex % colors.length];
          }
        },
        label: {
          show: true,
          position: 'top',
          fontSize: 12
        }
      }]
    };
  } catch (e) {
    console.error('渲染趋势图表出错:', e);
    chartError.value.inspection = true;
  }
};

// 辅助函数
const getHygieneStatus = (status) => {
  const statusMap = {
    1: '优秀',
    2: '良好',
    3: '合格',
    4: '不合格'
  };
  return statusMap[status] || '未知';
};

const getHygieneColor = (status) => {
  const colorMap = {
    1: '#52c41a', // 绿色
    2: '#a0d911', // 浅绿
    3: '#faad14', // 橙色
    4: '#f5222d'  // 红色
  };
  return colorMap[status] || '#d9d9d9';
};

const getProblemType = (type) => {
  const typeMap = {
    1: '卫生问题',
    2: '纪律问题',
    3: '安全问题',
    4: '其他问题'
  };
  return typeMap[type] || '未知类型';
};

const getProblemColor = (type) => {
  const colorMap = {
    1: '#13c2c2', // 青色
    2: '#1890ff', // 蓝色
    3: '#722ed1', // 紫色
    4: '#eb2f96'  // 粉色
  };
  return colorMap[type] || '#d9d9d9';
};

const formatDate = (dateStr) => {
  if (!dateStr) return '';
  // 格式: 2023-06-01 -> 06/01
  const parts = dateStr.split('-');
  if (parts.length >= 3) {
    return `${parts[1]}/${parts[2]}`;
  }
  return dateStr;
};

onMounted(() => {
  processData();
});
</script>

<style scoped>
.achievement-container {
  height: 100vh; /* 根据需要设置固定高度 */
  overflow-y: auto; /* 允许垂直滚动 */
  padding: 10px; /* 内边距 */
}

.dashboard-container {
  max-width: 800px;
  margin: 0 auto;
}

.dashboard {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.chart-card, .ai-card {
  background: white;
  border-radius: 12px;
  padding: 16px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.chart-title, .ai-title {
  margin: 0 0 16px 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  text-align: center;
}

.chart-wrapper {
  width: 100%;
  height: 320px;
  position: relative;
}

.chart-error {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  color: #f5222d;
  font-size: 14px;
}

.ai-content {
  font-size: 14px;
  line-height: 1.8;
  color: #444;
}

.ai-content strong {
  color: #1890ff;
  font-weight: 600;
}

@media (max-width: 576px) {
  .chart-wrapper {
    height: 280px;
  }

  .chart-title, .ai-title {
    font-size: 15px;
    margin-bottom: 12px;
  }

  .ai-content {
    font-size: 13px;
  }

  .chart-card, .ai-card {
    padding: 12px;
  }
}
</style>